<template>
    <div class="variable-list-panel">
        <div class="panel-header">
            <h3>设备监控 - {{ deviceName }}</h3>
            <div class="panel-actions">
                <!-- 需要在调试模式下显示写入/读取按钮 -->
                <a-button v-if="isDebugMode" size="small" icon="form" @click="writeSelectedVariable">写入选中变量</a-button>
                <a-button v-if="isDebugMode" size="small" icon="search" @click="readSelectedVariable">读取选中变量</a-button>
                <a-button v-if="allowedVariableDebug" size="small" :icon="variableDebugButtonIcon" :style="variableDebugButtonStyle" @click="variableDebug">{{ variableDebugButtonText }}</a-button>
                <a-button size="small" icon="reload" @click="refreshData">刷新</a-button>
            </div>
        </div>
        
        <div class="panel-content">
            <a-table
                :columns="dynamicColumns"
                :data-source="deviceVariables"
                row-key="id"
                bordered
                size="middle"
                :pagination="false"
                :loading="tableLoading"
                :row-selection="rowSelection"
            >
                <template slot="index" slot-scope="text, record, index">
                    {{ index + 1 }}
                </template>
                <template slot="status" slot-scope="text, record">
                    <span class="status-indicator" :class="record.status">
                        {{ record.status === 'normal' ? '●' : '○' }}
                    </span>
                </template>
                <template slot="debug" slot-scope="text, record">
                    <div class="debug-controls">
                        <a-input 
                            size="small" 
                            :value="debugValues[record.id]"
                            placeholder="输入值"
                            @input="updateDebugValue(record.id, $event.target.value)"
                        />
                        <a-tooltip title="读取">
                            <a-button 
                                type="link"
                                size="small" 
                                icon="search"
                                style="margin-right: 4px;"
                                @click="readVariable(record)"
                            />
                        </a-tooltip>
                        <a-tooltip title="写入">
                            <a-button 
                                type="link"
                                size="small" 
                                icon="form"
                                @click="writeVariable(record)"
                            />
                        </a-tooltip>
                    </div>
                </template>
                <template slot="action" slot-scope="text, record">
                    <a-button type="link" icon="edit" @click="editVariable(record.id)" />
                    <a-button type="link" icon="delete" @click="deleteVariable(record.id)" />
                </template>
            </a-table>
            
            <!-- Bottom actions and pagination -->
            <div class="table-footer">
                <div class="table-actions">
                    <a-button 
                        type="primary" 
                        icon="plus" 
                        :disabled="!activeDeviceId"
                        @click="addVariable"
                    >
                        新建监控
                    </a-button>
                    <a-button 
                        type="primary"
                        icon="plus-square" 
                        :disabled="!activeDeviceId"
                        @click="addBatchVariables"
                    >
                        批量添加
                    </a-button>
                    <a-button icon="download" @click="exportData">导出数据</a-button>
                    <a-button icon="bar-chart" @click="showStatistics">统计信息</a-button>
                </div>
                <a-pagination
                    :total="totalItems"
                    :show-size-changer="true"
                    :show-quick-jumper="true"
                    :show-total="total => `共 ${total} 条`"
                    :page-size-options="['10', '20', '50', '100']"
                    @change="handlePageChange"
                    @showSizeChange="handleSizeChange"
                />
            </div>
        </div>

        <!-- 变量属性弹窗 -->
        <variable-properties-modal
            :visible="variableModalVisible"
            :variable-data="editingVariableData"
            :port-proto-type="portProtoType"
            @ok="handleVariableModalOk"
            @cancel="handleVariableModalCancel"
        />

        <!-- 批量添加变量弹窗 -->
        <batch-variables-modal
            :visible="batchModalVisible"
            :port-proto-type="portProtoType"
            @ok="handleBatchModalOk"
            @cancel="handleBatchModalCancel"
        />

        <!-- 统计信息弹窗 -->
        <a-modal
            title="统计信息"
            :visible="statisticsVisible"
            :footer="null"
            width="600px"
            @cancel="statisticsVisible = false"
        >
            <div class="statistics-content">
                <a-row :gutter="16">
                    <a-col :span="12">
                        <a-statistic title="总变量数" :value="statistics.totalVariables" />
                    </a-col>
                    <a-col :span="12">
                        <a-statistic title="异常变量" :value="statistics.errorVariables" />
                    </a-col>
                </a-row>
                <a-row :gutter="16" style="margin-top: 16px;">
                    <a-col :span="12">
                        <a-statistic title="正常变量" :value="statistics.normalVariables" />
                    </a-col>
                    <a-col :span="12">
                        <a-statistic title="离线变量" :value="statistics.offlineVariables" />
                    </a-col>
                </a-row>
            </div>
        </a-modal>
    </div>
</template>

<script>
import VariablePropertiesModal from './VariablePropertiesModal.vue'
import BatchVariablesModal from './BatchVariablesModal.vue'
import tabManager from '@/api/tab-manager'
import createVariableProperties from './VariableProperties.js'
import { mapGetters } from 'vuex'
import { getGatewayConfig } from '@/config/gateway-config'
import { GATEWAY_CONFIGS } from '@/config/gateway-config'

export default {
    name: 'VariableListPanel',
    components: {
        VariablePropertiesModal,
        BatchVariablesModal
    },
    props: {
        activeDeviceId: { type: [Number, String], default: null },
        deviceName: { type: String, default: '未命名设备' },
        portName: { type: String, default: '未命名端口' },
        devices: { type: Array, default: () => [] },
        portProtoType: { type: String, default: '' }
    },
    data() {
        return {
            // 变量数据
            variables: [],
            
            // 分页配置
            currentPage: 1,
            pageSize: 10,
            
            // 弹框控制
            variableModalVisible: false,
            statisticsVisible: false,
            batchModalVisible: false,
            
            // 表单数据
            editingVariableData: null,
            batchVariablesData: [],
            
            // 加载状态
            tableLoading: false,
            
            // 统计数据
            statistics: {
                totalVariables: 0,
                errorVariables: 0,
                normalVariables: 0,
                offlineVariables: 0
            },

            // 变量调试模式
            variableDebugButtonText: '进入变量调试模式',
            variableDebugButtonIcon: 'bug',
            variableDebugButtonStyle: 'background-color: #ffffff;',
            isDebugMode: false,
            debugValues: {},
            
            // 多选功能
            selectedRowKeys: []
        }
    },
    computed: {
        ...mapGetters('groupTree', ['deviceConnection', 'selectedDeviceInfo']),

        // 获取当前设备的更新模式
        currentDeviceUpdateMode() {
            if (!this.selectedDeviceInfo) {
                return 'ethernet' // 默认为网络模式
            }

            // 如果直接有updateMode属性，使用它
            if (this.selectedDeviceInfo.updateMode) {
                return this.selectedDeviceInfo.updateMode
            }

            // 根据设备类型获取updateMode
            const deviceType = this.selectedDeviceInfo.gatewayType || this.selectedDeviceInfo.deviceType
            const config = GATEWAY_CONFIGS[deviceType]
            
            if (config && config.hardwareInfo && config.hardwareInfo.updateMode) {
                return config.hardwareInfo.updateMode
            }

            return 'ethernet' // 默认为网络模式
        },

        // 判断是否允许变量调试,serialport不允许调试
        allowedVariableDebug() {
            return this.currentDeviceUpdateMode !== 'serialport'
        },

        deviceVariables() {
            // 根据当前选中的设备生成监控数据
            const device = this.devices.find(d => d.id === this.activeDeviceId)
            if (!device) return []
            
            // 确保 variables 是数组，避免 filter 报错
            if (!Array.isArray(this.variables)) {
                return []
            }
            
            console.log('🔍 [VariableListPanel] 设备变量列表:', this.variables)
            const filteredData = this.variables
                .filter(v => v.monitor_device_id === this.activeDeviceId)
                .map(variable => ({
                    id: variable.id,
                    name: variable.name,
                    value: variable.extra.dataType,
                    unit: variable.extra.unit,
                    address: variable.extra.general.address,
                    register: variable.extra.general.type
                }))

            // 计算分页数据
            const startIndex = (this.currentPage - 1) * this.pageSize
            const endIndex = startIndex + this.pageSize
            return filteredData.slice(startIndex, endIndex)
        },
        
        totalItems() {
            return this.variables.filter(v => v.monitor_device_id === this.activeDeviceId).length
        },
        
        dynamicColumns() {
            const baseColumns = [
                { title: '序号', dataIndex: 'index', width: 40, scopedSlots: { customRender: 'index' } },
                { title: '状态', dataIndex: 'status', width: 30, scopedSlots: { customRender: 'status' } },
                { title: '名称', dataIndex: 'name', width: 100 },
                { title: '数据类型', dataIndex: 'value', width: 40 },
                { title: '单位', dataIndex: 'unit', width: 40 },
                { title: '地址', dataIndex: 'address', width: 80 },
                { title: '类型', dataIndex: 'register', width: 120 },
                { title: '操作', dataIndex: 'action', width: 100, scopedSlots: { customRender: 'action' } }
            ]
            
            if (this.isDebugMode) {
                const debugColumn = {
                    title: '变量调试操作',
                    dataIndex: 'debug',
                    width: 160,
                    scopedSlots: { customRender: 'debug' }
                }
                return [debugColumn, ...baseColumns]
            }
            
            return baseColumns
        },
        
        rowSelection() {
            // 只在调试模式下显示checkbox
            if (!this.isDebugMode) {
                return null
            }
            
            return {
                selectedRowKeys: this.selectedRowKeys,
                onChange: this.onSelectChange,
                onSelectAll: this.onSelectAll
            }
        }
    },
    watch: {
        activeDeviceId: {
            handler(newDeviceId, oldDeviceId) {
                console.log('🔄 [VariableListPanel] 选中设备变化:', { old: oldDeviceId, new: newDeviceId })
                if (newDeviceId !== oldDeviceId) {
                    // 清空选中状态
                    this.selectedRowKeys = []
                    this.loadVariables()
                }
            },
            immediate: true
        },
        portProtoType: {
            handler(newProtoType, oldProtoType) {
                console.log('🔄 [VariableListPanel] 端口协议类型变化:', { old: oldProtoType, new: newProtoType })
            },
            immediate: true
        }
    },
    mounted() {
        // 确保 variables 在组件初始化时是数组
        if (!Array.isArray(this.variables)) {
            this.variables = []
        }
        
        // 示例：设置分组设备id（根据实际需求调整）
        // 这里可以根据当前选中的设备或其他逻辑来设置分组设备id
        // this.$store.dispatch('global/setCurrentGroupDeviceId', this.activeDeviceId)
    },
    beforeDestroy() {
        // 组件销毁前清除分组设备id（可选）
        // this.$store.dispatch('global/clearCurrentGroupDeviceId')
    },
    methods: {
        // 分页方法
        handlePageChange(page) {
            console.log('📄 [VariableListPanel] 页码改变:', page)
            this.currentPage = page
        },

        handleSizeChange(current, size) {
            console.log('📏 [VariableListPanel] 每页条数改变:', { current, size })
            this.pageSize = size
            this.currentPage = 1
        },

        // 设置分组设备id的方法（可以在需要的地方调用）
        setGroupDeviceId(groupDeviceId) {
            console.log('🔄 [VariableListPanel] 设置分组设备id:', groupDeviceId)
            this.$store.dispatch('global/setCurrentGroupDeviceId', groupDeviceId)
        },
        
        // 清除分组设备id的方法
        clearGroupDeviceId() {
            console.log('🔄 [VariableListPanel] 清除分组设备id')
            this.$store.dispatch('global/clearCurrentGroupDeviceId')
        },
        
        // 获取当前分组设备id的方法
        getCurrentGroupDeviceId() {
            return this.$store.getters['global/getCurrentGroupDeviceId']
        },

        // 加载变量数据
        async loadVariables() {
            console.log('🔍 [VariableListPanel] 加载变量数据')
            try {
                // 检查是否有设备数据，如果没有设备则跳过变量加载
                if (!this.devices || this.devices.length === 0 || !this.activeDeviceId) {
                    console.log('⚠️ [VariableListPanel] 暂无设备数据，跳过变量加载', {
                        devicesCount: this.devices ? this.devices.length : 'null',
                        activeDeviceId: this.activeDeviceId
                    })
                    this.variables = []
                    return
                }
                
                this.tableLoading = true
                const response = await tabManager.monitor.getVariableList(this.activeDeviceId)
                
                // 检查响应状态
                if (response.code === 0) {
                    this.variables = []
                    // 后端返回的是JSON字符串，需要解析
                    const rawData = JSON.parse(response.data)
                    rawData.forEach(element => {
                        this.variables.push(JSON.parse(element.extra))
                    })
                    
                    console.log('✅ [VariableListPanel] 变量数据加载成功', { 
                        count: this.variables.length,
                        deviceId: this.activeDeviceId,
                        variables: this.variables
                    })
                } else {
                    console.warn('⚠️ [VariableListPanel] 变量数据加载异常:', response.message)
                    this.$message.warning(response.message || '获取变量数据异常')
                    this.variables = []
                }
            } catch (error) {
                console.error('❌ [VariableListPanel] 加载变量失败:', error)
                this.$message.error('变量数据加载失败')
                this.variables = []
            } finally {
                this.tableLoading = false
            }
        },

        // 更新统计数据
        updateStatistics() {
            // 获取当前设备的所有变量，而不是只获取当前页的变量
            const allDeviceVars = this.variables.filter(v => v.monitor_device_id === this.activeDeviceId)
            
            // 确保 allDeviceVars 是数组，避免 filter 报错
            if (!Array.isArray(allDeviceVars)) {
                this.statistics = {
                    totalVariables: 0,
                    errorVariables: 0,
                    normalVariables: 0,
                    offlineVariables: 0
                }
                return
            }
            
            this.statistics = {
                totalVariables: allDeviceVars.length,
                errorVariables: allDeviceVars.filter(v => v.status === 'error').length,
                normalVariables: allDeviceVars.filter(v => v.status === 'normal').length,
                offlineVariables: allDeviceVars.filter(v => v.status === 'offline').length
            }
        },

        // 变量操作方法
        async addVariable() {
            try {
                // 需要根据GATEWAY_CONFIGS中的硬件信息(variableCount)，来限制添加变量的数量
                // 根据设备类型获取updateMode
                const deviceType = this.selectedDeviceInfo.gatewayType || this.selectedDeviceInfo.deviceType
                const gatewayConfig = getGatewayConfig(deviceType)
                const variableCount = gatewayConfig.hardwareInfo.variableCount
                // 获取硬件数量
                const res = await tabManager.monitor.getHardwareCount(this.selectedDeviceInfo.id)
                if (res.code === 0) {
                    const data = JSON.parse(res.data)
                    if (data.variable >= variableCount) {
                        this.$message.error(`不能添加变量已达到最大限制，最大限制为${variableCount}`)
                        return
                    }
                }
                console.log('➕ [VariableListPanel] 打开添加监控变量弹窗')
                
                // 检查是否有选中的设备
                if (!this.activeDeviceId) {
                    console.log('⚠️ [VariableListPanel] 没有选中设备，无法添加变量')
                    this.$message.warning('请先选择一个设备再添加监控变量')
                    return
                }
                
                this.editingVariableData = null
                this.variableModalVisible = true                
            } catch (error) {
                console.error('❌ [VariableListPanel] 添加变量失败:', error)
                this.$message.error('添加变量失败')
            }
        },

        async editVariable(variableId) {
            console.log('✏️ [VariableListPanel] 编辑变量', { variableId })
            
            // 从本地变量列表中查找对应的变量
            const variable = this.variables.find(v => v.id === variableId)
            
            if (variable) {
                this.editingVariableData = variable
                this.variableModalVisible = true
                console.log('✅ [VariableListPanel] 获取变量详情成功', this.editingVariableData)
            } else {
                this.$message.error('未找到对应的变量')
                console.error('❌ [VariableListPanel] 在变量列表中未找到variableId:', variableId)
            }
        },

        async deleteVariable(variableId) {
            console.log('🗑️ [VariableListPanel] 删除变量', { variableId })
            try {
                await this.$confirm({
                    title: '确认删除',
                    content: '确定要删除这个监控变量吗？',
                    onOk: async() => {
                        const res = await tabManager.monitor.deleteVariable(variableId)
                        
                        // 检查返回状态
                        if (res.code === 0) {
                            this.$message.success('变量删除成功')
                            await this.loadVariables()
                            console.log('✅ [VariableListPanel] 变量删除操作完成', { variableId })
                        } else {
                            this.$message.error(res.msg || '变量删除失败')
                            console.error('❌ [VariableListPanel] 变量删除失败:', res.msg)
                        }
                    }
                })
            } catch (error) {
                console.error('❌ [VariableListPanel] 删除变量失败:', error)
                this.$message.error('删除变量失败')
            }
        },

        async refreshData() {
            console.log('🔄 [VariableListPanel] 刷新变量数据')
            await this.loadVariables()
            this.$message.success('变量数据已刷新')
            console.log('✅ [VariableListPanel] 变量数据刷新成功')
        },

        async variableDebug() {
            if (this.variableDebugButtonText === '进入变量调试模式') {
                this.$message.success('已经进入变量调试模式')
                this.variableDebugButtonStyle = 'color: #ff4d4f;'
                this.variableDebugButtonIcon = 'pause'
                this.variableDebugButtonText = '退出变量调试模式'
                this.isDebugMode = true
                this.debugValues = {}
            } else {
                this.$message.success('已经退出变量调试模式')
                this.variableDebugButtonStyle = 'background-color: #ffffff;'
                this.variableDebugButtonIcon = 'bug'
                this.variableDebugButtonText = '进入变量调试模式'
                this.isDebugMode = false
                this.debugValues = {}
                // 退出调试模式时清空选中状态
                this.selectedRowKeys = []
            }
        },

        // 调试相关方法
        updateDebugValue(variableId, value) {
            this.$set(this.debugValues, variableId, value)
        },

        // 多选相关方法
        onSelectChange(selectedRowKeys, selectedRows) {
            console.log('🔄 [VariableListPanel] 选择变化:', { selectedRowKeys, selectedRows })
            this.selectedRowKeys = selectedRowKeys
        },
        
        onSelectAll(selected, selectedRows, changeRows) {
            console.log('🔄 [VariableListPanel] 全选变化:', { selected, selectedRows, changeRows })
            if (selected) {
                this.selectedRowKeys = this.deviceVariables.map(item => item.id)
            } else {
                this.selectedRowKeys = []
            }
        },
        
        // 读取选中变量
        async readSelectedVariable() {
            if (!this.checkParams()) {
                return
            }

            if (this.selectedRowKeys.length === 0) {
                this.$message.warning('请先选择要读取的变量')
                return
            }
            
            console.log('📖 [VariableListPanel] 读取选中变量:', this.selectedRowKeys)
            try {
                const selectedVariables = this.deviceVariables.filter(variable => 
                    this.selectedRowKeys.includes(variable.id)
                )
                // 批量读取变量
                this.readMultiVariable(selectedVariables)
                console.log('✅ [VariableListPanel] 批量读取完成:', selectedVariables)
            } catch (error) {
                console.error('❌ [VariableListPanel] 批量读取变量失败:', error)
                this.$message.error('批量读取失败')
            }
        },

        async writeSelectedVariable() {
            if (!this.checkParams()) {
                return
            }

            if (this.selectedRowKeys.length === 0) {
                this.$message.warning('请先选择要写入的变量')
                return
            }
            
            console.log('📖 [VariableListPanel] 写入选中变量:', this.selectedRowKeys)
            try {
                // 需要过滤没有填写值的变量
                const selectedVariables = this.deviceVariables.filter(variable => 
                    this.selectedRowKeys.includes(variable.id) &&
                    this.debugValues[variable.id]
                )
                if (selectedVariables.length === 0) {
                    this.$message.warning('请先输入要写入的值')
                    return
                }
                // 批量写入变量
                this.writeMultiVariable(selectedVariables)
                console.log('✅ [VariableListPanel] 批量写入完成:', selectedVariables)
            } catch (error) {
                console.error('❌ [VariableListPanel] 批量写入变量失败:', error)
                this.$message.error('批量写入失败')
            }
        },

        async readVariable(record) {
            if (!this.checkParams()) {
                return
            }

            console.log('📖 [VariableListPanel] 读取变量:', record)
            this.readMultiVariable([record])
        },

        async writeVariable(record) {
            if (!this.checkParams()) {
                return
            }

            console.log('📖 [VariableListPanel] 写入变量:', record)

            const value = this.debugValues[record.id]
            if (!value) {
                this.$message.warning('请先输入要写入的值')
                return
            }

            this.writeMultiVariable([record])
        },

        async readMultiVariable(vars) {
            const hide = this.$message.loading('正在读取变量...', 0)
            try {
                const jsonData = this.packageVariableData(true, vars)
                const res = await tabManager.monitor.readVariable(jsonData)
                if (res.code === 0) {
                    // 读取成功后，将数据赋值给debugValues
                    const dataJson = JSON.parse(res.data)
                    const data = dataJson.value
                    // data是一个对象，键是变量名，值是变量值，需要根据vars的变量名称更新this.debugValues的值
                    if (data && typeof data === 'object') {
                        Object.keys(data).forEach(varName => {
                            const variable = vars.find(v => v.name === varName)
                            if (variable) {
                                this.debugValues[variable.id] = data[varName]
                            }
                        })
                    }
                    this.$message.success('读取成功')
                } else {
                    this.$message.error('读取失败: ' + res.msg)
                }
            } catch (error) {
                console.error('❌ [VariableListPanel] 读取变量失败:', error)
                this.$message.error('读取失败')
            } finally {
                hide()
            }
        },

        async writeMultiVariable(vars) {
            const hide = this.$message.loading('正在写入变量...', 0)
            try {
                const jsonData = this.packageVariableData(false, vars)
                const res = await tabManager.monitor.writeVariable(jsonData)
                if (res.code === 0) {
                    this.$message.success('写入成功')
                } else {
                    this.$message.error('写入失败: ' + res.msg)
                }                
            } catch (error) {
                console.error('❌ [VariableListPanel] 写入变量失败:', error)
                this.$message.error('写入失败')
            } finally {
                hide()
            }
        },

        packageVariableData(isRead, vars) {
            const arrayName = isRead ? 'VariableName' : 'WriteData'
            const func = isRead ? 'Read' : 'Write'
            const portName = this.portName
            const deviceName = this.deviceName

            const params = this.getParams()

            // 读取数据需要转成数组
            const arrayReadData = []
            const writeData = {}
            if (isRead) {
                vars.forEach(item => {
                    arrayReadData.push(item.name)
                })                
            } else {
                // 写数据是一个object
                vars.forEach(item => {
                    const value = this.debugValues[item.id]
                    const floatValue = parseFloat(value)
                    writeData[item.name] = floatValue
                })

            }

            const dataVars = {
                'Function': func,
                'PortName': portName, // 获取端口名称
                'DeviceName': deviceName, // 获取设备名称
                [arrayName]: isRead ? arrayReadData : writeData
            }

            const data = {
                'Vars': dataVars,
                'Params': params
            }

            const jsonData = JSON.stringify(data)
            console.log('🔍 [VariableListPanel] 打包变量数据:', jsonData)
            return jsonData
        },

        checkParams() {
            if (!this.deviceConnection.ipAddress || !this.deviceConnection.port) {
                this.$message.error('请先在 "设备操作Tab" 中配置IP地址和端口')
                return false
            }
            return true
        },

        getParams() {
            if (!this.deviceConnection.ipAddress || !this.deviceConnection.port) {
                this.$message.error('请先在 "设备操作Tab" 中配置IP地址和端口')
                return
            }

            return {
                ip: this.deviceConnection.ipAddress,
                port: parseInt(this.deviceConnection.port)
            }
        },

        async exportData() {
            console.log('📤 [VariableListPanel] 导出变量数据为CSV格式', {
                activeDeviceId: this.activeDeviceId,
                deviceName: this.deviceName,
                totalVariables: this.variables.length
            })
            try {
                // 检查是否有选中的设备
                if (!this.activeDeviceId) {
                    this.$message.warning('请先选择一个设备')
                    console.warn('⚠️ [VariableListPanel] 未选择设备')
                    return
                }
                
                // 1. 获取当前设备的所有变量数据（不分页）
                const allDeviceVars = this.variables.filter(
                    v => v.monitor_device_id === this.activeDeviceId
                )
                
                console.log('🔍 [VariableListPanel] 筛选后的变量数据:', {
                    count: allDeviceVars.length,
                    data: allDeviceVars
                })
                
                if (!allDeviceVars || allDeviceVars.length === 0) {
                    this.$message.warning('当前设备没有可导出的变量数据')
                    console.warn('⚠️ [VariableListPanel] 当前设备无变量数据')
                    return
                }
                
                // 2. 转换为CSV格式
                const csvData = this.convertToCsvFormat(allDeviceVars)
                console.log('🔄 [VariableListPanel] CSV数据转换完成:', csvData)
                
                // 3. 生成CSV内容
                const csvContent = this.generateCsvString(csvData)
                console.log('📝 [VariableListPanel] CSV内容生成完成，长度:', csvContent.length)
                
                // 4. 保存CSV文件（用户选择保存位置）
                await this.downloadCsv(csvContent)
                
                this.$message.success(`数据导出成功，共导出 ${allDeviceVars.length} 条记录`)
                console.log('✅ [VariableListPanel] 变量数据导出成功', { count: allDeviceVars.length })
            } catch (error) {
                // 如果是用户取消操作，不显示错误消息
                if (error.message === '用户取消了保存操作') {
                    return
                }
                console.error('❌ [VariableListPanel] 导出数据失败:', error)
                this.$message.error(`导出失败: ${error.message}`)
            }
        },
        
        // 转换数据格式为CSV所需格式
        convertToCsvFormat(variables) {
            console.log('🔄 [VariableListPanel] 转换数据格式', { count: variables.length })
            return variables.map(variable => ({
                '名称': variable.name || '',
                '数据类型': variable.extra?.dataType || '',
                '单位': variable.extra?.unit || '',
                '地址': variable.extra?.general?.address || '',
                '类型': variable.extra?.general?.type || ''
            }))
        },
        
        // 生成CSV字符串（支持中文）
        generateCsvString(data) {
            console.log('📝 [VariableListPanel] 生成CSV字符串')
            // 表头
            const headers = ['名称', '数据类型', '单位', '地址', '类型']
            const headerRow = headers.join(',')
            
            // 数据行
            const dataRows = data.map(row => {
                return headers.map(header => {
                    const value = row[header] || ''
                    // 处理包含逗号、引号或换行符的值，需要用双引号包裹
                    const stringValue = String(value).replace(/"/g, '""')
                    // 如果值包含逗号、引号或换行符，需要用双引号包裹
                    if (stringValue.includes(',') || stringValue.includes('"') || stringValue.includes('\n')) {
                        return `"${stringValue}"`
                    }
                    return stringValue
                }).join(',')
            })
            
            // 添加BOM以支持Excel正确显示中文
            return '\uFEFF' + [headerRow, ...dataRows].join('\n')
        },
        
        // 下载CSV文件（让用户选择保存位置）
        async downloadCsv(csvContent) {
            console.log('💾 [VariableListPanel] 保存CSV文件')
            const timestamp = new Date().toISOString().split('T')[0]
            const suggestedFileName = `变量数据_${this.deviceName}_${timestamp}.csv`
            
            try {
                // 检查浏览器是否支持 File System Access API
                if ('showSaveFilePicker' in window) {
                    console.log('✅ [VariableListPanel] 使用 File System Access API')
                    // 使用现代 API 让用户选择保存位置
                    const fileHandle = await window.showSaveFilePicker({
                        suggestedName: suggestedFileName,
                        types: [{
                            description: 'CSV 文件',
                            accept: { 'text/csv': ['.csv'] }
                        }]
                    })
                    
                    // 创建可写流并写入内容
                    const writable = await fileHandle.createWritable()
                    await writable.write(csvContent)
                    await writable.close()
                    
                    console.log('✅ [VariableListPanel] CSV文件保存成功')
                } else {
                    console.log('⚠️ [VariableListPanel] 浏览器不支持 File System Access API，使用传统下载方式')
                    // 降级方案：使用传统的下载方式
                    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
                    const url = window.URL.createObjectURL(blob)
                    const link = document.createElement('a')
                    link.href = url
                    link.download = suggestedFileName
                    link.style.display = 'none'
                    
                    document.body.appendChild(link)
                    link.click()
                    
                    setTimeout(() => {
                        document.body.removeChild(link)
                        window.URL.revokeObjectURL(url)
                    }, 100)
                    
                    console.log('✅ [VariableListPanel] CSV文件下载触发成功（传统方式）')
                }
            } catch (error) {
                // 用户取消保存或其他错误
                if (error.name === 'AbortError') {
                    console.log('ℹ️ [VariableListPanel] 用户取消了保存操作')
                    throw new Error('用户取消了保存操作')
                } else {
                    console.error('❌ [VariableListPanel] 保存文件失败:', error)
                    throw error
                }
            }
        },

        showStatistics() {
            console.log('📊 [VariableListPanel] 显示统计信息')
            this.updateStatistics()
            this.statisticsVisible = true
            console.log('✅ [VariableListPanel] 统计信息弹窗已打开')
        },

        // 弹框处理方法
        async handleVariableModalOk(formData) {
            console.log('💾 [VariableListPanel] 保存变量设置', { formData, editingVariable: this.editingVariableData })
            try {
                if (this.editingVariableData && this.editingVariableData.id) {
                    // Edit
                    console.log('✏️ [VariableListPanel] 更新变量', { variableId: this.editingVariableData.id })
                    const res = await tabManager.monitor.updateVariable(this.editingVariableData.id, JSON.stringify(formData))
                    
                    // 检查返回状态
                    if (res.code === 0) {
                        this.$message.success('变量更新成功')
                        console.log('✅ [VariableListPanel] 变量更新成功', { variableId: this.editingVariableData.id })
                        await this.loadVariables()
                    } else {
                        this.$message.error(res.msg || '变量更新失败')
                        console.error('❌ [VariableListPanel] 变量更新失败:', res.msg)
                        return
                    }
                } else {
                    // Add
                    console.log('➕ [VariableListPanel] 创建新变量', { deviceId: this.activeDeviceId })
                    formData.monitor_device_id = this.activeDeviceId
                    const newVariableData = {
                        ...formData
                    }
                    const res = await tabManager.monitor.createVariable(JSON.stringify(newVariableData))
                    
                    console.log('🔍 [VariableListPanel] 创建新变量结果:', res)
                    // 检查返回状态
                    if (res.code === 0 && res.data) {
                        this.$message.success('变量创建成功')
                        
                        // 确保 variables 是数组
                        if (!Array.isArray(this.variables)) {
                            this.variables = []
                        }
                        
                        const data = JSON.parse(res.data)
                        // 如果API返回了新创建的变量数据，直接添加到本地列表
                        if (data) {
                            const newVariable = {
                                id: data.id,
                                name: data.name,
                                monitor_device_id: data.monitor_device_id,
                                extra: data.extra
                            }
                            console.log('🔍 [VariableListPanel] 新变量数据:', newVariable)
                            this.variables.push(newVariable)
                            this.updateStatistics()
                            console.log('✅ [VariableListPanel] 新变量已添加到本地列表', { variableId: newVariable.id, name: newVariable.name })
                        } else {
                            // 如果API没有返回变量数据，重新加载变量列表
                            await this.loadVariables()
                            console.log('✅ [VariableListPanel] 重新加载变量列表')
                        }
                    } else {
                        this.$message.error(res.msg || '变量创建失败')
                        console.error('❌ [VariableListPanel] 变量创建失败:', res.msg)
                        return
                    }
                }
                
                this.variableModalVisible = false
                
                // 如果是编辑模式，仍然需要重新加载数据以确保数据同步
                if (this.editingVariableData && this.editingVariableData.id) {
                    await this.loadVariables()
                }
                
                // 通知父组件数据已更新
                this.$emit('data-updated')
            } catch (error) {
                console.error('❌ [VariableListPanel] 变量操作失败:', error)
                this.$message.error('操作失败')
            }
        },

        handleVariableModalCancel() {
            console.log('❌ [VariableListPanel] 取消变量设置编辑')
            this.variableModalVisible = false
        },

        addBatchVariables() {
            console.log('📝 [VariableListPanel] 打开批量添加变量对话框')
            this.batchModalVisible = true
        },

        async handleBatchModalOk(data) {
            console.log('💾 [VariableListPanel] 批量保存变量设置', data)
            try {
                this.tableLoading = true
                const newVariableList = []
                const variableIndex = parseInt(data.variableIndex)
                const addressUnit = parseInt(data.addressUnit)
                const addressNum = parseInt(data.addressNum)
                let addressIncrement = 0// 地址递增
                // 获取硬件数量
                const deviceType = this.selectedDeviceInfo.gatewayType || this.selectedDeviceInfo.deviceType
                const gatewayConfig = getGatewayConfig(deviceType)
                const variableCount = gatewayConfig.hardwareInfo.variableCount                
                const response = await tabManager.monitor.getHardwareCount(this.selectedDeviceInfo.id)
                if (response.code === 0) {
                    const data = JSON.parse(response.data)
                    if (data.variable >= variableCount) {
                        this.$message.error(`添加${variableIndex} 变量数量已达到最大限制，最大限制为${variableCount}`)
                        return
                    }
                }
                for (let index = 0; index < variableIndex; index++) {
                    // 使用工厂函数创建新的变量对象
                    const newVariable = createVariableProperties()
                    // 赋值基本信息
                    newVariable.id = -1
                    newVariable.name = data.variableName + index.toString()
                    newVariable.monitor_device_id = this.activeDeviceId
                    // 需要展开赋值
                    newVariable.extra.alias = data.variableAlias + index.toString()
                    newVariable.extra.dataType = data.dataType
                    newVariable.extra.decimalPlaces = data.bitOffset
                    newVariable.extra.unit = data.unit
                    newVariable.extra.conversionFactor = data.conversionFactor
                    newVariable.extra.general.type = data.registerType
                    newVariable.extra.general.isHex = data.isHex
                    // 地址,如果是十六进制,则需要转换为十六进制
                    addressIncrement = addressNum + addressUnit * index
                    if (data.isHex) {
                        newVariable.extra.general.address = (addressIncrement).toString(16)
                    } else {
                        newVariable.extra.general.address = (addressIncrement).toString()
                    }
                    
                    console.log('🔍 [VariableListPanel] 新变量数据:', newVariable)
                    // this.variables.push(newVariable) 更新成功后重新加载变量列表
                    newVariableList.push(newVariable)
                }

                const res = await tabManager.monitor.createBatchVariable(JSON.stringify(newVariableList))
                if (res.code === 0) {
                    this.$message.success(`成功添加 ${variableIndex} 个变量`)
                } else {
                    this.$message.warning(`${variableIndex} 个变量添加失败`)
                }

                this.batchModalVisible = false
                // // 重新加载变量列表以确保数据同步
                await this.loadVariables()
                // // 通知父组件数据已更新
                // this.$emit('data-updated')
                // 暂时只关闭对话框，不执行具体操作
                this.batchModalVisible = false
            } catch (error) {
                console.error('❌ [VariableListPanel] 批量添加变量失败:', error)
                this.$message.error('批量添加失败')
            } finally {
                this.tableLoading = false
            }
        },

        handleBatchModalCancel() {
            console.log('❌ [VariableListPanel] 取消批量添加变量')
            this.batchModalVisible = false
        }
    }
}
</script>

<style scoped>
.variable-list-panel {
    height: 100%;
    display: flex;
    flex-direction: column;
    background: #fff;
}
.panel-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 12px 16px;
    border-bottom: 1px solid #d9d9d9;
    background: #fff;
}
.panel-header h3 {
    margin: 0;
    font-size: 14px;
    font-weight: 500;
    color: #333;
}
.panel-actions {
    display: flex;
    gap: 8px;
}
.panel-content {
    flex: 1;
    padding: 16px;
    overflow: auto;
}
.table-footer {
    margin-top: 16px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.table-actions {
    display: flex;
    gap: 8px;
}
.status-indicator {
    display: inline-block;
    width: 8px;
    height: 8px;
    border-radius: 50%;
    margin-right: 4px;
}
.status-indicator.normal {
    background-color: #52c41a;
}
.status-indicator.error {
    background-color: #ff4d4f;
}
.status-indicator.offline {
    background-color: #d9d9d9;
}
.statistics-content {
    padding: 16px 0;
}
.debug-controls {
    display: flex;
    align-items: center;
    gap: 4px;
    width: 100%;
}
.debug-controls .ant-input {
    flex: 1;
    margin-right: 4px;
}
.debug-controls .ant-btn {
    min-width: 24px;
    padding: 0 6px;
    flex-shrink: 0;
}
</style> 